package com.cqcetbbs.smartlab.cqcetbbs.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.cqcetbbs.smartlab.cqcetbbs.R;
import com.cqcetbbs.smartlab.cqcetbbs.activity.NewsDetailActivity;
import com.cqcetbbs.smartlab.cqcetbbs.activity.PublishArtActivity;
import com.cqcetbbs.smartlab.cqcetbbs.adapter.FragmentDetailAdapter;
import com.cqcetbbs.smartlab.cqcetbbs.javabean.new_art;
import com.cqcetbbs.smartlab.cqcetbbs.utils.MySnackbar;
import com.cqcetbbs.smartlab.cqcetbbs.utils.SpUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by user on 2017/9/20.
 * 详情页面
 */

public class FragmentDetailed extends BaseFragment {

    //发现页面数据key
    public static final String FRAGMENTTETAIL_FATA = "fragmentdetail_data";
    public static final String PAHT = "http://api.cqcetlab.com/Home/article/artlist";


    public static final int DATA = 0;
    public static final int MORE_DATA = 1;

    //网络异常
    public static final int IO_ERROR = 3;
    //请求失败
    public static final int FAILE = 2;

    //每次请求的数据个数
    public static final int COUNT = 5;
//    private MyListView myListView;
    private ListView listView;
    private int mIndex = 0;
    private FragmentDetailAdapter adapter;
//    private SwipeRefreshLayout swipeRefreshLayout;

    RefreshLayout refreshLayout;

    //diretcion:（true：下拉加载  false：上拉加载 ）
    private boolean diretcion = true;
    OkHttpClient client;
    FloatingActionButton fab;
    ArrayList<new_art.Art> artList;
    ArrayList<new_art.Art> MoreartList;
    private int page = 2;
    new_art new_art;
    Gson gson;
    Type listType;
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA:
                    if (TextUtils.isEmpty((String) msg.obj)) {
                        return;
                    }
                    gson = new Gson();
//                    listType = new TypeToken<ArrayList<Art>>() {
//                    }.getType();
//                    artList = gson.fromJson((String) msg.obj, listType);
                   // adapter = new FragmentDetailAdapter(activity, artList);

                    new_art = gson.fromJson((String) msg.obj,new_art.class);
                    artList =  new_art.getData();
                    adapter = new FragmentDetailAdapter(activity, new_art.getData());
                    listView.setAdapter(adapter);
                    break;
                case MORE_DATA:
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadmore();
                    if (!TextUtils.isEmpty((String) msg.obj)) {
                        page++;
                        MoreartList = null;
                        gson = new Gson();
//                        listType = new TypeToken<ArrayList<new_art.Art>>() {
//                        }.getType();
//                        MoreartList = gson.fromJson((String) msg.obj, listType);
                        new_art new_art_more = new new_art();
                        new_art_more = gson.fromJson((String) msg.obj,new_art.class);
                        MoreartList =   new_art_more.getData();
                        //将数据加入artList中
                        if (diretcion) {
                            //下拉加载数据添加到artList头部
                            artList.addAll(0, MoreartList);
                        } else {
                            //上拉加载数据添加到artList尾部
                            artList.addAll(artList.size(), MoreartList);
                        }
                        //刷新数据
                        adapter.notifyDataSetChanged();
//                        swipeRefreshLayout.setRefreshing(false);
//                        myListView.refreshComplete();
                        MySnackbar.ShowSnackbar(listView,"刷新了" + MoreartList.size() + "条数据");

                    } else {
                        MySnackbar.ShowSnackbar(listView,"刷新了" + MoreartList.size() + "条数据");
//                        swipeRefreshLayout.setRefreshing(false);
//                        myListView.refreshComplete();


                    }

                    break;

                //请求失败
                case IO_ERROR:
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadmore();
//                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(activity, "网络异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public View getInitView() {

        View view = View.inflate(activity, R.layout.fragment_detail, null);
//        swipeRefreshLayout = view.findViewById(R.id.srl);
//        myListView = view.findViewById(R.id.lv);


         listView = view.findViewById(R.id.listview);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadmore(false);

        //添加头布局
        View viewhead = View.inflate(activity, R.layout.fragment_detail_mylistview_header, null);
        listView.addHeaderView(viewhead);

        fab = view.findViewById(R.id.fab);
        return view;
    }


    @Override
    public void initData() {


        //加载上次缓存文件
        String data = SpUtils.getStringValues(activity, FRAGMENTTETAIL_FATA, "");
        Message msg = mhandler.obtainMessage(DATA, data);
        mhandler.sendMessage(msg);
        //请求网络
        postData();


        //设置圈圈颜色
//        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
//                R.color.colorAccent, R.color.colorPrimary,
//                R.color.colorAccent);

        //网络缓存


        setOnClickListener();


        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, PublishArtActivity.class);
                startActivity(intent);
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //将数据传递到NewsDetailActivity并显示出来
                if (l == -1) {
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("id", artList.get((int) l).getId() + "");
                Intent intent = new Intent(activity, NewsDetailActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });
    }

//
//    @Override
//    public void onResume() {
//        super.onResume();
//        postData();
//    }

    private void setOnClickListener() {
//        /**
//         * 下拉刷新
//         */
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //count:每次请求的数据个数，page:每次请求第几页，
//                        postmoreData(String.valueOf(COUNT), String.valueOf(page));
////                        postAsynHttp(String.valueOf(COUNT), String.valueOf(page));
//                        diretcion = true;
//                    }
//                }, 1500);
//            }
//
//
//        });
//        /**
//         * 上拉加载更多
//         */
//        myListView.setLoadMoreListener(new MyListView.LoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //count:每次请求的数据个数，page:每次请求第几页，
//                        postmoreData(String.valueOf(COUNT), String.valueOf(page));
//                        diretcion = false;
//                    }
//                }, 1500);
//
//            }
//        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //count:每次请求的数据个数，page:每次请求第几页，
                        postmoreData(String.valueOf(COUNT), String.valueOf(page));
//                        postAsynHttp(String.valueOf(COUNT), String.valueOf(page));
                        diretcion = true;
                    }
                }, 1500);
            }
        });

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //count:每次请求的数据个数，page:每次请求第几页，
                        postmoreData(String.valueOf(COUNT), String.valueOf(page));
                        diretcion = false;
                    }
                }, 1500);
            }
        });
    }


    // post请求后台数据（默认加载五条数据）
    private void postData() {
        client = new OkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Request request = new Request.Builder()
                        .url(PAHT)
                        .build();
                //新建一个线程，用于得到服务器响应的参数

                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        String Data = response.body().string();
                        SpUtils.setStringValues(activity, FRAGMENTTETAIL_FATA, Data);
                        //将服务器的数据(发现页面数据)保存在本地
                        Message msg = mhandler.obtainMessage(DATA, Data);
                        mhandler.sendMessage(msg);

                    } else {
                    }
                } catch (IOException e) {
                    Message msg = mhandler.obtainMessage(IO_ERROR);
                    mhandler.sendMessage(msg);
                }
            }
        }).start();

    }


    //加载更多数据,
    public void postmoreData(final String num, final String page) {

        client = new OkHttpClient();
        new Thread() {
            @Override
            public void run() {
                RequestBody body = new FormBody.Builder()
                        .add("num", num)
                        .add("page", page)
                        .build();
                Request request = new Request.Builder()
                        .url(PAHT)
                        .post(body)
                        .build();

                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String result = response.body().string();
                        Message msg = mhandler.obtainMessage(MORE_DATA, result);
                        mhandler.sendMessage(msg);
                    } else {
                    }
                } catch (Exception e) {
                    Message msg = mhandler.obtainMessage(IO_ERROR);
                    mhandler.sendMessage(msg);
                }

            }
        }.start();
    }

}
